<?php
/**
 * 通用方法控制器
 * User: lang@vip.deyi.com
 * Date: 2017/10/9
 * Time: 11:13
 */

namespace Apps\Acp\Controllers;

use Apps\Common\Constant\BusinessConstant;
use Apps\Common\Controller\AcpBaseController;
use Apps\Weixin\Models\WxAttach;
use Apps\Weixin\Services\WxResourceService;
use Deyi\Functions\HttpFunction;
use Deyi\Functions\RemoteFileFunction;
use Vendor\UEditor\UEditor;

class CommonController extends AcpBaseController
{
    public function uploadAction()
    {
        $weixin = $this->getParamValue('weixin', 0, 'int', true) ? true : false;
        $appId = $this->getParamValue('appid', '', 'string', true);
        $extname = strrchr(strtolower($_FILES['file']['name']), '.');

        $newfile = $_FILES['file']['tmp_name'] . $extname;
        if (!move_uploaded_file($_FILES['file']['tmp_name'], $newfile)) {
            static::errorThrow('移动文件失败!');
        }

        $result = false;

        if ($weixin) {
            $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=' . WxResourceService::getInstance()->getAuthorizerAccessToken($appId);
            $result = HttpFunction::uploadFileToUrl($newfile, 'buffer', $url);
            if ($result && ($json = json_decode($result)) && isset($json->url)) {
                $result = $json->url;
            }
        } else {
            $result = RemoteFileFunction::uploadSingleFile($newfile);
        }

        if (!$result) {
            unlink($newfile);
            static::errorThrow('上传文件出错');
        }

        $imgSize = getimagesize($newfile);
        $fileSize = filesize($newfile);
        $width = 0;
        $height = 0;
        if ($imgSize) {
            $width = $imgSize[0];
            $height = $imgSize[1];
        }
        unlink($newfile);

        WxAttach::getInstance()->insertByFields([
            'uid' => static::$userSession->id,
            'path' => $result,
            'width' => $width,
            'height' => $height,
            'size' => $fileSize,
            'filetype' => str_replace('.', '', $extname),
            'dateline' => time()
        ]);

        parent::renderSuccessJson([
            'url' => static::doAddImgUrlDomain($result),
            'path' => $result,
            'img_width' => $width,
            'img_height' => $height
        ]);
    }

    public function deleteFileAction()
    {
        $file = $this->getParamValue('file', null, null, true);

        if (strpos($file, 'http') === 0) {
            parent::renderSuccessJson([], '删除文件成功');
            return;
        }

        WxAttach::getInstance()->deleteByFields([
            'path' => $file,
            'uid' => static::$userSession->id
        ]);

        if (WxAttach::getInstance()->getAffectRows() > 0 && RemoteFileFunction::deleteFile($file)) {
            parent::renderSuccessJson([], '删除文件成功');
        } else {
            static::errorThrow('删除文件出错');
        }
    }

    public function ueditorUploadAction()
    {
        $action = $this->getParamValue('action');
        $start = $this->getParamValue('start', 0, 'int');
        $size = $this->getParamValue('size', BusinessConstant::PAGE_SIZE, 'int');
        if ($action == 'listimage') {
            $conditions = [];
            $conditions['uid'] = static::$userSession->id;
            $total = WxAttach::getInstance()->countListByConditions($conditions);
            $list = [];
            if ($total) {
                $res = WxAttach::getInstance()->getListByConditions($conditions, $start, $size);
                foreach ($res as $v) {
                    $list[] = [
                        'url' => $this->doAddImgUrlDomain($v->path),
                        'mtime' => $v->dateline
                    ];
                }
            }

            $ret = [
                'state' => 'SUCCESS',
                'list' => $list,
                'start' => $start,
                'total' => $total
            ];

        } else {
            $ret = UEditor::getReturn($action);
        }

        if (isset($ret['url'])) {
            if (strpos($action, 'upload') === 0) {
                WxAttach::getInstance()->insertByFields([
                    'uid' => static::$userSession->id,
                    'path' => $ret['url'],
                    'width' => $ret['width'],
                    'height' => $ret['height'],
                    'size' => $ret['size'],
                    'filetype' => str_replace('.', '', $ret['type']),
                    'dateline' => time()
                ]);
            }
            $ret['url'] = static::doAddImgUrlDomain($ret['url']);
        }

        if (is_array($ret)) {
            echo json_encode($ret, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
        } else {
            echo $ret;
        }
    }

    public function jsConfigAction()
    {
        $this->view->setVars([
            'imgurl' => static::$_config->project->imageurl,
            'uploadUrl' => '/acp/common/upload'
        ]);
    }
}